from apps.goods.models import SKUImage
from rest_framework import serializers
from apps.goods.models import SKU
from fdfs_client.client import Fdfs_client


class ImageSkuModelSerializer(serializers.ModelSerializer):

    class Meta:
        model = SKUImage
        fields = '__all__'

    # 序列化器原有的updata 不能满足我们需求，需要重写，将更新数据保存到数据库中
    def update(self, instance, validated_data):
        '''

        :param instance: 要更新的模型类
        :param validated_data: 需要更新的字典数据
        :return:
        '''
        # 创建fastdfs客户端
        client = Fdfs_client('utils/fastdfs/client.conf')
        # 获取我们需要的image数据
        try:
            image = validated_data.get('image')
        except Exception as e:
            raise ValueError
        # 上传文件到fastdfs服务器
        res = client.upload_appender_by_buffer(image.read())
        if res.get('Status') != 'Upload successed.':
            raise ValueError
        # 将数据保存到数据中
        # print(instance.image)
        instance.image = res.get('Remote file_id')
        instance.save()
        return instance





class SimpleSKUViewSerializer(serializers.ModelSerializer):

    class Meta:
        model = SKU
        fields = ['id', 'name']

